// ============================================================================
// 关键字窗口管理页面
// ============================================================================

import React, { useState, useEffect } from 'react'
import { keywordWindowService, KeywordWindowSummary, KeywordWindowDetails } from '../services/keyword-window-service'
import { useNotifications } from '../hooks/use-notifications'
import { EditKeywordWindowModal } from '../components/EditKeywordWindowModal'
import { logger } from '../utils/logger'

/**
 * 关键字窗口管理页面组件
 */
export const KeywordWindowPage: React.FC = () => {
  const [windows, setWindows] = useState<KeywordWindowSummary[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [showEditModal, setShowEditModal] = useState(false)
  const [selectedWindow, setSelectedWindow] = useState<KeywordWindowDetails | null>(null)
  const [historyCrawlInfo, setHistoryCrawlInfo] = useState<{
    keywords: string[]
    total: number
    config: {
      historyCrawlInterval: number
      historyCrawlIntervalHours: number
    }
  } | null>(null)
  const { showSuccess, showError } = useNotifications()

  // 加载数据
  useEffect(() => {
    loadData()
    
    // 定时刷新数据
    const interval = setInterval(loadData, 30000) // 30秒刷新一次
    
    return () => {
      clearInterval(interval)
    }
  }, [])

  /**
   * 加载所有数据
   */
  const loadData = async () => {
    try {
      setLoading(true)
      await Promise.all([
        loadWindows(),
        loadHistoryCrawlInfo()
      ])
    } catch (error) {
      logger.error('加载数据失败', error)
      showError('加载数据失败', `${(error as Error).message}`)
    } finally {
      setLoading(false)
    }
  }

  /**
   * 加载关键字窗口列表
   */
  const loadWindows = async () => {
    try {
      const windowList = await keywordWindowService.getAllWindows()
      setWindows(windowList)
    } catch (error) {
      logger.error('加载关键字窗口失败', error)
      throw error
    }
  }

  /**
   * 加载历史爬取信息
   */
  const loadHistoryCrawlInfo = async () => {
    try {
      const info = await keywordWindowService.getKeywordsNeedingHistoryCrawl()
      setHistoryCrawlInfo(info)
      logger.debug('历史爬取信息加载成功', {
        total: info.total,
        interval: info.config.historyCrawlInterval
      })
    } catch (error) {
      logger.error('加载历史爬取信息失败', {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : undefined
      })
      // 不抛出错误，这个信息不是必需的
      // 设置为 null 以便 UI 可以显示相应状态
      setHistoryCrawlInfo(null)
    }
  }

  /**
   * 编辑关键字窗口
   */
  const editWindow = async (keyword: string) => {
    try {
      const windowDetails = await keywordWindowService.getKeywordWindow(keyword)
      setSelectedWindow(windowDetails)
      setShowEditModal(true)
    } catch (error) {
      logger.error('获取关键字窗口详情失败', error)
      showError('获取窗口详情失败', `${(error as Error).message}`)
    }
  }

  /**
   * 重置关键字窗口
   */
  const resetWindow = async (keyword: string) => {
    if (!confirm(`确定要重置关键字"${keyword}"的窗口设置吗？这将清除时间范围和统计信息。`)) {
      return
    }

    try {
      await keywordWindowService.resetKeywordWindow(keyword)
      showSuccess('窗口已重置', `关键字"${keyword}"的窗口设置已重置`)
      await loadData()
    } catch (error) {
      logger.error('重置窗口失败', error)
      showError('重置窗口失败', `${(error as Error).message}`)
    }
  }

  /**
   * 删除关键字窗口
   */
  const deleteWindow = async (keyword: string) => {
    if (!confirm(`确定要删除关键字"${keyword}"的窗口吗？这将清除所有相关数据。`)) {
      return
    }

    try {
      await keywordWindowService.deleteKeywordWindow(keyword)
      showSuccess('窗口已删除', `关键字"${keyword}"的窗口已删除`)
      await loadData()
    } catch (error) {
      logger.error('删除窗口失败', error)
      showError('删除窗口失败', `${(error as Error).message}`)
    }
  }

  /**
   * 过滤关键字窗口
   */
  const filteredWindows = windows.filter(window =>
    window.keyword.toLowerCase().includes(searchTerm.toLowerCase())
  )

  /**
   * 格式化窗口大小显示
   */
  const formatWindowSize = (windowSize: string): string => {
    if (!windowSize) return '未设置'
    
    // 解析窗口大小，假设格式为 "startTime - endTime"
    const parts = windowSize.split(' - ')
    if (parts.length === 2) {
      const startTime = keywordWindowService.formatDateTime(parts[0])
      const endTime = keywordWindowService.formatDateTime(parts[1])
      return `${startTime} - ${endTime}`
    }
    
    return windowSize
  }

  /**
   * 获取历史状态显示
   */
  const getHistoryStatus = (window: KeywordWindowSummary): { text: string; color: string } => {
    if (window.hasMoreHistory) {
      const isInHistoryCrawlList = historyCrawlInfo?.keywords.includes(window.keyword)
      if (isInHistoryCrawlList) {
        return { text: '待爬取', color: 'text-orange-600 bg-orange-100' }
      } else {
        return { text: '有历史', color: 'text-blue-600 bg-blue-100' }
      }
    } else {
      return { text: '已完成', color: 'text-green-600 bg-green-100' }
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-lg text-gray-600">加载中...</div>
      </div>
    )
  }

  return (
    <div className="p-6 space-y-6">
      {/* 页面标题和控制 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">关键字窗口管理</h1>
          <p className="text-sm text-gray-600 mt-1">管理关键字爬取时间窗口和历史进度</p>
        </div>

        <div className="flex items-center space-x-4">
          {/* 搜索框 */}
          <div className="relative">
            <input
              type="text"
              placeholder="搜索关键字..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {/* 刷新按钮 */}
          <button
            onClick={loadData}
            className="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 text-sm font-medium"
          >
            刷新数据
          </button>
        </div>
      </div>

      {/* 统计信息 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-blue-600">
            {windows.length}
          </div>
          <div className="text-sm text-gray-600">总窗口数</div>
        </div>

        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-green-600">
            {windows.filter(w => !w.hasMoreHistory).length}
          </div>
          <div className="text-sm text-gray-600">历史完成</div>
        </div>

        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-orange-600">
            {historyCrawlInfo?.total || 0}
          </div>
          <div className="text-sm text-gray-600">待历史爬取</div>
        </div>

        <div className="bg-white p-4 rounded-lg border">
          <div className="text-2xl font-bold text-purple-600">
            {windows.reduce((sum, w) => sum + w.totalPosts, 0).toLocaleString()}
          </div>
          <div className="text-sm text-gray-600">总次数</div>
        </div>
      </div>

      {/* 关键字窗口列表 */}
      <div className="bg-white rounded-lg border">
        <div className="px-6 py-4 border-b">
          <h2 className="text-lg font-semibold text-gray-900">关键字窗口列表</h2>
          <p className="text-sm text-gray-600 mt-1">
            显示 {filteredWindows.length} / {windows.length} 个关键字窗口
          </p>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  关键字
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  时间窗口
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  次数
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  历史状态
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  最后更新
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {filteredWindows.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-8 text-center text-gray-500">
                    {searchTerm ? '未找到匹配的关键字窗口' : '暂无关键字窗口'}
                  </td>
                </tr>
              ) : (
                filteredWindows.map((window) => {
                  const historyStatus = getHistoryStatus(window)

                  return (
                    <tr key={window.keyword} className="hover:bg-gray-50">
                      <td className="px-6 py-4">
                        <div>
                          <div className="text-sm font-medium text-gray-900">
                            {window.keyword}
                          </div>
                          <div className="text-xs text-gray-500">
                            关键字
                          </div>
                        </div>
                      </td>

                      <td className="px-6 py-4">
                        <div className="text-sm text-gray-900">
                          {formatWindowSize(window.windowSize)}
                        </div>
                      </td>

                      <td className="px-6 py-4">
                        <div className="text-sm font-medium text-gray-900">
                          {window.totalPosts.toLocaleString()}
                        </div>
                        <div className="text-xs text-gray-500">
                          总次数
                        </div>
                      </td>

                      <td className="px-6 py-4">
                        <span className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${historyStatus.color}`}>
                          {historyStatus.text}
                        </span>
                      </td>

                      <td className="px-6 py-4 text-sm text-gray-900">
                        {keywordWindowService.formatDateTime(window.lastUpdate)}
                      </td>

                      <td className="px-6 py-4">
                        <div className="flex items-center space-x-2">
                          <button
                            onClick={() => editWindow(window.keyword)}
                            className="text-blue-600 hover:text-blue-900 text-sm"
                          >
                            编辑
                          </button>

                          <button
                            onClick={() => resetWindow(window.keyword)}
                            className="text-yellow-600 hover:text-yellow-900 text-sm"
                          >
                            重置
                          </button>

                          <button
                            onClick={() => deleteWindow(window.keyword)}
                            className="text-red-600 hover:text-red-900 text-sm"
                          >
                            删除
                          </button>
                        </div>
                      </td>
                    </tr>
                  )
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 编辑窗口模态框 */}
      {showEditModal && selectedWindow && (
        <EditKeywordWindowModal
          window={selectedWindow}
          onClose={() => {
            setShowEditModal(false)
            setSelectedWindow(null)
          }}
          onSuccess={() => {
            setShowEditModal(false)
            setSelectedWindow(null)
            loadData()
          }}
        />
      )}
    </div>
  )
}
